package com.softa.web.controller.system;

import javax.servlet.http.HttpServletRequest;

import com.softa.bean.LoginReq;
import com.softa.enummodel.LoginEnum;
import com.softa.shiro.authc.CaptchaAuthenticationToken;
import com.softa.utils.IpUtil;
import com.softa.web.controller.base.BaseController;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 
* @ClassName: LoginController
* @Description: TODO
* @author yangl
* @date 2015-6-5 下午1:35:36
*
 */
@Controller
@RequestMapping("/login")
public class LoginController extends BaseController {

    @RequestMapping()
    public String showLoginForm(HttpServletRequest req, Model model) {
        String exceptionClassName = (String)req.getAttribute("shiroLoginFailure");
        String error = null;
        if(UnknownAccountException.class.getName().equals(exceptionClassName)) {
            error = "用户名/密码错误";
        } else if(IncorrectCredentialsException.class.getName().equals(exceptionClassName)) {
            error = "用户名/密码错误";
        } else if(exceptionClassName != null) {
            error = "其他错误：" + exceptionClassName;
        }
        logger.error(error);
        model.addAttribute("error", error);
        return "login";
    }

    @RequestMapping(value = "/checkAdminLogin", method = RequestMethod.POST)
    @ResponseBody
    public Integer checkAdminLogin(HttpServletRequest req, Model model, LoginReq loginReq) {
        //成功
        Integer status = 1;
        //请输入用户名或密码
        if(StringUtils.isEmpty(loginReq.getUserName()) ||
                StringUtils.isEmpty(loginReq.getPassword())){
            return 0;
        }
        String ip = IpUtil.getIpAddr(req);
        CaptchaAuthenticationToken token = new CaptchaAuthenticationToken(loginReq.getUserName(), loginReq.getPassword(),
                false, ip, null);
        token.setLoginType(loginReq.getLoginType());
        Subject subject = SecurityUtils.getSubject();
        try {
          //登录，即身份验证
            subject.login(token);
        } catch (AuthenticationException e) {
            //身份验证失败
            logger.error("身份验证失败，异常：{}", e.getMessage());
            status = 2;
        }
        return status;
    }



}
